// config.js
// ====================== 创建提示框 ======================
// 样式
const style = document.createElement('style');
style.textContent = `
  .collect-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 9999;
    display: none;
    justify-content: center;
    align-items: center;
  }
  .collect-message {
    background: white;
    padding: 20px 40px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    font-size: 16px;
    color: #333;
  }
  .collect-message.success { color: #4CAF50; }
  .collect-message.error { color: #f44336; }
`;
document.head.appendChild(style);

// 提示框元素
const overlay = document.createElement('div');
overlay.className = 'collect-overlay';
const message = document.createElement('div');
message.className = 'collect-message';
overlay.appendChild(message);
document.body.appendChild(overlay);

const href = location.href;

// 获取规格层级结构
function getSpecsStructure() {
    const specs = [];
    if(href.indexOf('version=0') > -1) {
        const specBlocks = document.querySelectorAll('.sku-module-wrapper.sku-prop-module'); // 规格区块（如颜色、尺寸）
        specBlocks.forEach(block => {
            const title = block.querySelector('.sku-prop-module-name')?.innerText.trim() || '未知规格'; // 规格名称（如“颜色”）
            const options = Array.from(block.querySelectorAll('.prop-item-wrapper .prop-item .prop-item-inner-wrapper')).map(item => ({
                element: item, // 规格选项的DOM元素
                name: item.querySelector('.prop-name')?.innerText, // 规格值（如“红色”）
            }));
            specs.push({ title, options });
        });
    }else {
        const specBlocks = document.querySelectorAll('.module-od-sku-selection .feature-item'); // 规格区块（如颜色、尺寸）
        specBlocks.forEach(block => {
            const title = block.querySelector('.feature-item-label')?.innerText.trim() || '未知规格'; // 规格名称（如“颜色”）
            const options = Array.from(block.querySelectorAll('.transverse-filter .sku-filter-button')).map(item => ({
                element: item, // 规格选项的DOM元素
                name: item.querySelector('.label-name')?.innerText, // 规格值（如“红色”）
            }));
            if(options.length > 0) specs.push({ title, options });
        });
    }
    return specs;
}

// 获取价格规格行
function getPriceSpecsStructure() {
    let specs = {};
    const href = location.href;
    if(href.indexOf('version=0') > -1) {
        const specBlocks = document.querySelectorAll('.sku-module-horizon-list'); // 规格区块（如颜色、尺寸）
        specBlocks.forEach(block => {
            const title = block.querySelector('.sku-prop-module-name')?.innerText.trim() || '未知规格'; // 规格名称（如“颜色”）
            const options = Array.from(block.querySelectorAll('.count-widget-wrapper .sku-item-wrapper')).map(item => ({
                element: item, // 规格选项的DOM元素
                name: item.querySelector('.sku-item-name')?.innerText, // 规格值（如“红色”）
                price: item.querySelector('.discountPrice-price')?.innerText.replace('元', ''),
            }));
            specs = { title, options };
        });
    }else {
        const specBlocks = document.querySelectorAll('.module-od-sku-selection .feature-item'); // 规格区块（如颜色、尺寸）
        specBlocks.forEach(block => {
            if(block.querySelector('.expand-view-list') !== null) {
                const title = block.querySelector('.feature-item-label')?.innerText.trim() || '未知规格'; // 规格名称（如“颜色”）
                const options = Array.from(block.querySelectorAll('.expand-view-list .expand-view-item')).map(item => ({
                    element: item, // 规格选项的DOM元素
                    name: item.querySelector('.item-label')?.innerText, // 规格值（如“红色”）
                    price: item.querySelector('.item-price-stock')?.innerText.replace('¥', ''),
                }));
                specs = { title, options };
            }
        });
    }
    return specs;
}

// 生成所有可能的组合
function generateCombinations(specs) {
    const combinations = [];
    const backtrack = (currentSpecIndex, currentPath) => {
        if (currentSpecIndex === specs.length) {
            combinations.push([...currentPath]);
            return;
        }
        for (const option of specs[currentSpecIndex].options) {
            currentPath.push({...option, title: specs[currentSpecIndex].title});
            backtrack(currentSpecIndex + 1, currentPath);
            currentPath.pop();
        }
    };
    backtrack(0, []);
    return combinations;
}

// 通过背景图获取图片的url
function getBackgroundImageUrl(element) {
    if(element) {
        const computedStyle = window.getComputedStyle(element);
        const backgroundImage = computedStyle.getPropertyValue("background-image");
        // 使用正则匹配 URL 内容
        const urlMatch = backgroundImage.match(/url\(["']?(.*?)["']?\)/);
        // 提取路径（处理引号和括号）
        return urlMatch ? urlMatch[1] : null
    }else {
        return ''
    }
}

// 控制提示框显示/隐藏的函数
function showMessage(text, isSuccess = true) {
    message.className = `collect-message ${isSuccess ? 'success' : 'error'}`;
    message.textContent = text;
    overlay.style.display = 'flex';
}

function hideMessage() {
    overlay.style.display = 'none';
}

const ALIBABA_CONFIG = {
    // 通用配置（适用于所有1688页面）
    common: {
        matches: ["*://*.1688.com/*"], // 匹配所有1688页面
        buttonStyle: {
            zIndex: 1000,
            padding: '5px 20px',
            background: '#ff5500',
            borderRadius: '5px',
            color: 'white',
            border: 'none',
            cursor: 'pointer'
        },
    },

    // 不同页面类型的独立配置
    pages: [
        {
            // 1688详情页
            name: "1688详情页",
            // 通过 URL 或 DOM 特征识别页面类型
            condition: {
                urlPattern: "*://detail.1688.com", // URL 匹配规则
                // 或通过 DOM 特征识别（如页面中存在特定元素）
                domSelector: "", // 仅当该元素存在时生效
            },
            cardSelector: "html", // 商品卡片选择器
            extractor: async () => {
                const specs = getSpecsStructure();
                const combinations = generateCombinations(specs);
                const results = [];
                for (let i = 0; i < combinations.length; i++) {
                    const combination = combinations[i];
                    let isValid = true;
                    let imgUrl = ''
                    // 依次点击当前组合的规格
                    for(let i = 0; i < combination.length; i++) {
                        const option = combination[i];
                        try {
                            const isExist = option.element.classList.contains('active')
                            if(!isExist) {
                                option.element.click(); // 模拟点击
                            }
                            await new Promise(resolve => setTimeout(resolve, 200)); // 等待价格更新
                            imgUrl = option.element.querySelector('img')?.src || getBackgroundImageUrl(option.element.querySelector('.prop-img')) || imgUrl
                        } catch (error) {
                            isValid = false;
                            break;
                        }
                    }

                    // 如果组合有效，记录价格
                    if (isValid) {
                        const priceSpec = getPriceSpecsStructure()
                        const specs = {}
                        for(let i = 0; i < combination.length; i++) {
                            specs[combination[i].title] = combination[i].name
                        }
                        for(let j = 0; j < priceSpec['options'].length; j++) {
                            imgUrl = priceSpec['options'][j].element.querySelector('img')?.src || getBackgroundImageUrl(priceSpec['options'][j].element.querySelector('.sku-item-image')) || imgUrl
                            specs[priceSpec['title']] = priceSpec['options'][j].name
                            const price = priceSpec['options'][j].price
                            results.push({ specs, price, imgUrl });
                        }
                    }
                    // 更新进度提示
                    showMessage(`已采集 ${i + 1}/${combinations.length} 种组合...`);
                }

                let imageTexts
                if(href.indexOf('version=0') > -1) {
                    imageTexts = document.querySelectorAll('.content-detail img')
                }else {
                    const hostElement = document.querySelector('.html-description');
                    if (hostElement.shadowRoot) {
                        const shadowRoot = hostElement.shadowRoot;
                        imageTexts = shadowRoot.querySelectorAll("#detail img")
                    } else {
                        console.error('宿主元素未附加 Shadow Root 或模式为 closed');
                    }
                }
                let imageText = []
                for (let i = 0; i < imageTexts.length; i++) {
                    const imgUrl = href.indexOf('version=0') > -1 ? imageTexts[i]?.getAttribute("data-lazyload-src") : imageTexts[i]?.getAttribute("src")
                    imageText.push(imgUrl)
                }

                return {skus: results, imageTexts: imageText};
            },
            buttonStyle: {
                position: 'fixed',
                bottom: '50px',
                left: '10px'
            },
        },
    ],
};
